package com.ai.zuochengyun.phase01.class03;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

/**
 * 求树的最大宽度
 */
public class Code15_TreeMaxWidth {

    public static int maxWidthUseMap(BinaryTreeNode head) {
        if (head == null) {
            return 0;
        }

        Queue<BinaryTreeNode> queue = new LinkedList<>();
        queue.add(head);

        // key 在哪一层， value
        Map<BinaryTreeNode, Integer> levelMap = new HashMap<>();

        // 当前正在统计哪一层的宽度
        int curLevel = 1;
        // 当前层，也就是curLevel层，宽度目前是多少
        int curLevelNodes = 0;

        int max = 0;
        while (!queue.isEmpty()) {
            BinaryTreeNode cur = queue.poll();
            int curNodeLevel = levelMap.get(cur);

            if (cur.left != null) {
                levelMap.put(cur.left, curNodeLevel+1);
                queue.add(cur.left);
            }
            if (cur.right != null) {
                levelMap.put(cur.right, curNodeLevel+1);
                queue.add(cur.right);
            }

            if (curNodeLevel == curLevel) {
                curLevelNodes++;
            } else {
                max = Math.max(max, curLevelNodes);
                curLevel++;
                curLevelNodes = 1;
            }
        }

        return max;
    }

    public static int maxWidthNoMap(BinaryTreeNode head) {
        if (head == null) {
            return 0;
        }

        Queue<BinaryTreeNode> queue = new LinkedList<>();
        queue.add(head);

        int max = 0;
        int curLevelNodes = 0;
        BinaryTreeNode curEnd = head;
        BinaryTreeNode nextEnd = null;

        while (!queue.isEmpty()) {
            BinaryTreeNode cur = queue.poll();
            if (cur.left != null) {
                queue.add(cur.left);
                nextEnd = cur.left;
            }
            if (cur.right != null) {
                queue.add(cur.right);
                nextEnd = cur.right;
            }

            // 弹出节点的时候，curLevelNodes累加
            curLevelNodes++;
            // 判断cur节点是否是这一层的最后一个节点
            if (cur == curEnd) {
                max = Math.max(max, curLevelNodes);

                // curEnd指向nextEnd，表明结束上一层，来到下一层继续判断
                curEnd = nextEnd;

                // 统计数清零
                curLevelNodes =0;
                nextEnd = null;
            }
        }
        return max;
    }

}
